#include "event_loop_thread_pool.h"
#include "event_loop.h"
#include "event_loop_thread.h"
#include <cstdio>
#include <vector>

EventLoopThreadPool::EventLoopThreadPool(EventLoop *base_loop, const std::string &name_arg)
    : base_loop_(base_loop), name_(name_arg), started_(false), num_threads_(0), next_(0) {}

EventLoopThreadPool::~EventLoopThreadPool() {

}

void EventLoopThreadPool::start(const ThreadInitCallback &cb) {
    started_ = true;

    for (int i = 0; i < num_threads_; ++i) {
        char buf[name_.size() + 32];
        snprintf(buf, sizeof buf, "%s%d", name_.c_str(), i);
        EventLoopThread *t = new EventLoopThread(cb, buf);
        threads_.push_back(std::unique_ptr<EventLoopThread>(t));
        loops_.push_back(t->start_loop()); // 底层创建线程，绑定一个EventLoop,并返回loop地址
    }

    // 整个服务端只有一个线程，运行着baseloop
    if (num_threads_ == 0 && cb) {
        cb(base_loop_);
    }
}

// 如果工作在多线程，base_loop_默认以轮询的防止分配channel给subloop
EventLoop *EventLoopThreadPool::get_next_loop() {
    EventLoop *loop = base_loop_;

    if (!loops_.empty()) {
        loop = loops_[next_];
        ++next_;
        if (next_ >= loops_.size()) {
            next_ = 0;
        }
    }
    return loop;
}

std::vector<EventLoop *> EventLoopThreadPool::get_all_loops() {
    if (loops_.empty()) {
        return std::vector<EventLoop *>(1, base_loop_);
    } else {
        return loops_;
    }
}